extends HBoxContainer
class_name StateBar
enum STATE {
	POWER,
	SHIELD,
	ARMOR_BREAK,
	WEAK,
	NOTHING,
	TEMP_POWER,
	TEMP_MAX_HEALTH,
	COUNTER_ATTACK,
	ROUND_POWER,
	ANGER_ADDITION,
	ROUND_SHIELD,
	SHIELD_CUMULATION,
	CANT_DRAW_CARD,
	UNYIELDING,
	NEXT_POINT,
	DARK_MARK_15,
	DARK_SEED_16
}

var state_map = {}
var temp_power_index = 0
var temp_max_health_index = 0


func state_change(state_type: STATE, v = 0, d = 0):
	if state_type == STATE.TEMP_POWER:
		var temp_key = str(state_type) + "_" + str(temp_power_index)
		var state:BufferState = Globals.ALL_STATE_TRES_DICT.state_dict[state_type].create_instance(v, d)
		state_map[temp_key] = state.init_scene()
		add_child(state_map[temp_key])
		return
	if state_type == STATE.TEMP_MAX_HEALTH:
		var temp_key = str(state_type) + "_" + str(temp_max_health_index)
		var state = Globals.ALL_STATE_TRES_DICT.state_dict[state_type].create_instance(v, d)
		state_map[temp_key] = state.init_scene()
		add_child(state_map[temp_key])
		return
	if !state_map.has(state_type):
		var state = Globals.ALL_STATE_TRES_DICT.state_dict[state_type].create_instance(v, d)
		var sc = state.init_scene()
		state_map[state_type] = sc
		add_child(state_map[state_type])
	else:
		var s = state_map[state_type]
		s.update_state(v, d)


func state_delete(state_type: STATE):
	if !state_map.has(state_type):
		return
	var s = state_map[state_type]
	if s != null:
		s.queue_free()
		state_map.erase(state_type)


func get_state(state_type: STATE):
	if !state_map.has(state_type):
		return null
	else:
		return state_map[state_type]


func before_round(target):
	get_children().sort_custom(sort_ascending)
	for s in get_children():
		s.before_round(target)
		if s.state.show_duration and s.state.duration == 0:
			state_map.erase(s.state.id)
			s.queue_free()


func after_round(target):
	get_children().sort_custom(sort_ascending)
	for s in get_children():
		s.after_round(target)
		if s.state.show_duration and s.state.duration == 0:
			state_map.erase(s.state.id)
			s.queue_free()


func sort_ascending(a, b):
	if a.state.id < b.state.id:
		return true
	return false


func state_match(type, value, duration):
	if value != 0:
		state_change(type, value, duration)
	else:
		state_delete(type)
	return

func init_state(state: BasicCharacterState):
	var value = state.shield
	state_match(StateBar.STATE.SHIELD, value, 0)
	value = state.armor_break
	state_match(StateBar.STATE.ARMOR_BREAK, value, value)
	value = state.counter_attack
	state_match(StateBar.STATE.COUNTER_ATTACK, value, 0)
	value = state.unyielding
	state_match(StateBar.STATE.UNYIELDING, value, 0)

